<script setup lang="ts">
import {ref, onMounted, onUnmounted, nextTick} from 'vue';

const props = defineProps({
  t: {
    type: String,
    default: () => ''
  },
  position: {
    type: Object,
    default: () => ({x: 0, y: 0})
  }
});

const emit = defineEmits(['closed']);

const dropdownElement = ref<HTMLElement | null>(null); // 使用 ref 获取子组件的 DOM 元素

// 方法：隐藏下拉菜单
const hideDropdown = () => {
  emit('closed');
};

// 监听全局点击事件
const handleClickOutside = (event: MouseEvent) => {
  const target = event.target as HTMLElement;
  if (dropdownElement.value && !dropdownElement.value.contains(target)) {
    hideDropdown(); // 如果点击在外部，则隐藏下拉菜单
  } else {
  }
};

// 挂载时添加事件监听
onMounted(() => {
  nextTick(() => {
    // setTimeout(() => {
    //   document.addEventListener('click', handleClickOutside);
    // })
    const observer = new MutationObserver(() => {
      document.addEventListener('click', handleClickOutside);
      observer.disconnect(); // 停止监听
    });

    observer.observe(document.body, {
      childList: true,
      subtree: true
    });
  })
});

// 卸载时移除事件监听
onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside);
});
</script>

<template>
  <div
      class="list"
      :style="{ top: `${position.y}px`, left: `${position.x}px` }"
      ref="dropdownElement"
      @click.stop=""
  >
    <header class="list-header" v-show="t.length > 0">{{ t }}</header>
    <div class="list-content">
      <slot></slot>
    </div>
  </div>
</template>

<style scoped lang="scss">
.list {
  width: 178px;
  min-height: 176px;
  background: #1d1c27;
  border-radius: 10px;
  position: fixed;
  transition: all 0.3s ease;

  &-header {
    height: 32px;
    line-height: 32px;
    padding: 0 16px;
    border-bottom: 1px solid #e8e8e8;
  }

  &-content {
    padding: 16px;
  }

  &::after {
    content: '';
    position: absolute;
    top: -10px;
    left: 50%;
    transform: translateX(-50%);
    width: 0;
    height: 0;
    border-left: 10px solid transparent;
    border-right: 10px solid transparent;
    border-bottom: 10px solid #1d1c27;
  }
}
</style>